﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TinyContactManager.Web.Internal.Data;
using TinyContactManager.Web.Internal.Entities;
using TinyContactManager.Web.Models;

namespace TinyContactManager.Web.Controllers
{
    public class MailingsController : ApiController
    {
        private readonly IDbContext _dbContext;
        private readonly Func<DateTime> _systemTime;

        public MailingsController(IDbContext dbContext, Func<DateTime> systemTime)
        {
            _dbContext = dbContext;
            _systemTime = systemTime;
        }

        [HttpGet]
        public HttpResponseMessage GetMailingContacts(int[] contactIds)
        {
            return new HttpResponseMessage();
        }

        [HttpPost]
        public HttpResponseMessage CreateForContacts(int[] contactIds)
        {
            var set = _dbContext.Set<Mailing>();
            foreach (var contactId in contactIds)
            {
                set.Add(new Mailing { Contact_Id = contactId, Date = _systemTime() });
            }
            _dbContext.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }

        [HttpPut]
        public HttpResponseMessage ContactResponded(ContactIdModel contact)
        {
            var date = _systemTime();
            var pastDate = date.AddMonths(-12);
            var set = _dbContext.Set<Mailing>();
            var record = set
                .Where(x => x.Date > pastDate)
                .OrderByDescending(x => x.Date)
                .FirstOrDefault(x => x.Contact_Id == contact.Id);
            if(record != null)
            {
                record.Responded = date;
            }
            _dbContext.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
    }
}